package code.cando;

/**
 * author : yeswater
 * date : 2023/12/5
 * 删除链表的倒数第 N 个节点
 * <p>
 * 1 怎么定位倒数第 N 个
 * 2 删除: cur.next = cur.next.next;
 */

public class T019 {
    public static void main(String[] args) {

    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode fast = pre, slow = pre;
        // 定位
        while(n != 0) {
            fast = fast.next;
            n--;
        }
        while(fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        // 删除
        slow.next = slow.next.next;
        return pre.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
